package com.fc.happyteam.shiro.filter;

import com.fc.happyteam.dtos.ResponseJson;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

import static com.fc.happyteam.utils.HttpContextUtils.isAjax;
import static com.fc.happyteam.utils.HttpContextUtils.sendJSON;

/**
 * Kickout user if he login from different client in same time
 */
@Getter
@Setter
public class KickoutSessionFilter extends AccessControlFilter {

    private final static String ATTIBUTE_KICK_OUT = "kickout";

    private CacheManager cacheManager;

    private SessionManager sessionManager;

    private String cacheName = "kickout_cache";

    private int maxSession = 1;

    private boolean kickoutAfter = false;

    private String kickoutUrl = "/";

    private Cache<String, Deque<Serializable>> cache = null;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        return (maxSession <= 0) || (!subject.isAuthenticated() && !subject.isRemembered());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        Session session = subject.getSession();

        String username = (String)(session.getAttribute("username"));
        Serializable sessionId = session.getId();

        Cache<String, Deque<Serializable>> cache = getCache();
        Deque<Serializable> deque = cache.get(username);
        if (deque == null) {
            synchronized (cache) {
                deque = cache.get(username);
                if (deque == null) {
                    deque = new LinkedList<>();
                    cache.put(username, deque);
                }
            }
        }

        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute(ATTIBUTE_KICK_OUT) == null) {
            deque.push(sessionId);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId;
            if (kickoutAfter) { //如果踢出后者
                kickoutSessionId = deque.removeFirst();
            } else { //否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            try {
                Session kickoutSession =
                        sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute(ATTIBUTE_KICK_OUT, true);
                }
            } catch (Exception e) {//ignore exception
            }
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute(ATTIBUTE_KICK_OUT) != null) {
            //会话被踢出了
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }
            if (!isAjax(request)) {
                saveRequest(request);
                WebUtils.issueRedirect(request, response, kickoutUrl);
            } else {
                sendJSON((HttpServletResponse) response, ResponseJson.error(HttpServletResponse.SC_UNAUTHORIZED, "账号在别处登陆"));
            }

            return false;
        }
        return true;
    }

    private Cache<String, Deque<Serializable>> getCache() {
        if (this.cache != null) {
            return this.cache;
        }
        return cacheManager.getCache(cacheName);
    }
}
